<script setup>
  import { onMounted, ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { getFolderTreeService, transferFilesService } from '@/api/file.js'
  import { useFileStore } from '@/stores/modules/file.js'
  import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    files: {
      type: Array,
      required: true
    }
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const fileStore = useFileStore()
  const treeData = ref([])
  const isLoading = ref(false)
  const selectedFolderId = ref(null)

  const loadFolderTree = async () => {
    isLoading.value = true
    try {
      const res = await getFolderTreeService()
      treeData.value = res.data
    } catch (error) {
      console.error(error)
    } finally {
      isLoading.value = false
    }
  }

  // 处理节点选择
  const handleNodeClick = data => {
    selectedFolderId.value = data.id
  }

  // 处理文件转移
  const handleTransfer = async () => {
    if (!selectedFolderId.value) {
      ElMessage.warning('请选择目标文件夹')
      return
    }

    // 检查是否在同一目录
    if (selectedFolderId.value === fileStore.parentId) {
      ElMessage.warning('不能移动到当前目录')
      return
    }

    // 检查是否在同一路径下
    const currentFiles = props.files.map(file => file.fileId)
    if (currentFiles.includes(selectedFolderId.value)) {
      ElMessage.warning('不能移动到所选文件夹内')
      return
    }

    try {
      const fileIds = props.files.map(file => file.fileId)
      await transferFilesService(fileIds, selectedFolderId.value)
      ElMessage.success(props.files.length > 1 ? '文件批量转移成功' : '文件转移成功')
      emit('success')
      handleClose()
    } catch (error) {
      ElMessage.error('转移失败：' + error.message)
    }
  }

  // 关闭对话框
  const handleClose = () => {
    emit('update:modelValue', false)
    // 重置状态
    selectedFolderId.value = null
  }

  onMounted(() => {
    if (props.modelValue) {
      loadFolderTree()
    }
  })

  // 监听对话框显示状态
  watch(
    () => props.modelValue,
    newVal => {
      if (newVal) {
        loadFolderTree()
      }
    }
  )
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    :model-value="modelValue"
    title="转移到"
    width="480px"
    @close="handleClose"
    @update:model-value="val => emit('update:modelValue', val)"
  >
    <div v-loading="isLoading" class="folder-tree-container">
      <el-tree
        v-if="treeData.length > 0"
        :data="treeData"
        :highlight-current="true"
        :props="{
          children: 'children',
          label: 'label'
        }"
        default-expand-all
        node-key="id"
        @node-click="handleNodeClick"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <SvgIcon
              :name="node.expanded ? 'file-type-folder-open' : 'file-type-folder'"
              class="folder-icon"
              height="24px"
              width="24px"
            />
            <span class="label">{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
      <el-empty v-else description="暂无文件夹" />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleTransfer">确认转移</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
  .folder-tree-container {
    height: 400px;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  .custom-tree-node {
    display: flex;
    align-items: center;

    .folder-icon {
      margin-right: 8px;
    }

    .label {
      font-size: 14px;
      line-height: 24px;
    }
  }

  :deep(.el-tree-node__content) {
    height: 32px;
  }

  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: #ecf5ff;
    color: #409eff;
  }

  :deep(.el-tree-node__children) {
    padding-left: 24px;
  }

  // 隐藏默认的树形展开图标
  :deep(.el-tree-node__expand-icon) {
    display: none;
  }
</style>
